package handlers

import (
	"data_service/models"
	"data_service/server"
	"errors"
	"gorm.io/gorm"
	"log"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// 初始化动态业务服务
var postService = server.NewPostService()

// CreatePost 创建新动态
func CreatePost(c *gin.Context) {
	var post models.Post
	if err := c.ShouldBindJSON(&post); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的参数"})
		return
	}
	// 输出接收到的用户ID日志
	log.Printf("Received post data: UserID=%d, Content=%s", post.UserID, post.Content)
	if post.UserID == 0 {
		log.Printf("警告：接收到的用户ID为空")
	}
	post.CreatedAt = time.Now()
	if err := postService.CreatePost(&post); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建动态失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"isLiked": true, "likes": post.Likes})
}

// GetRecentPosts 获取最新动态（默认10条）
func GetRecentPosts(c *gin.Context) {
	posts, err := postService.GetRecentPosts(10)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取动态失败"})
		return
	}
	c.JSON(http.StatusOK, posts)
}

// GetAllPosts 获取所有动态
func GetAllPosts(c *gin.Context) {
	// 获取用户ID
	userIdStr := c.Query("user_id")
	userId, _ := strconv.ParseUint(userIdStr, 10, 32)

	posts, err := postService.GetAllPosts(uint(userId))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, posts)
}

// GetPostsByUser 获取指定用户的所有动态
func GetPostsByUser(c *gin.Context) {
	userId := c.Param("userId")
	posts, err := postService.GetPostsByUser(userId)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户动态失败"})
		return
	}
	c.JSON(http.StatusOK, posts)
}

// LikePost 给动态点赞
func LikePost(c *gin.Context) {
	// 获取路径参数
	postIdStr := c.Param("id")
	postId, err := strconv.Atoi(postIdStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的动态ID格式"})
		return
	}

	// 获取用户ID（实际应用中应从认证中间件获取）
	userIdStr := c.GetHeader("X-User-ID")
	if userIdStr == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "未授权访问"})
		return
	}
	userId, err := strconv.Atoi(userIdStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户ID格式"})
		return
	}

	// 调用服务层处理点赞
	isLiked, likes, err := postService.LikePost(uint(postId), uint(userId))
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			c.JSON(http.StatusNotFound, gin.H{"error": "动态不存在"})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "点赞操作失败"})
		}
		return
	}

	// 返回结果
	c.JSON(http.StatusOK, gin.H{
		"isLiked": isLiked,
		"likes":   likes,
	})
}

// DeletePost 删除动态
func DeletePost(c *gin.Context) {
	postId := c.Param("id")
	if err := postService.DeletePost(postId); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除动态失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "删除成功"})
}
